package com.study.leetcode;

public class Solution_42 {
    public static int trap(int[] height) {
        int ans = 0;
        int len = height.length;
        int[] preMax = new int[len];
        int[] sufMax = new int[len];
        preMax[0] = height[0];
        for (int i = 1; i < len; i++) {
            preMax[i] = Math.max(preMax[i - 1], height[i]);
        }

        sufMax[len - 1] = height[len - 1];
        for (int i = len - 2; i >= 0; i--) {
            sufMax[i] = Math.max(sufMax[i + 1], height[i]);
        }

        for (int i = 0; i < len; i++) {
            ans += Math.min(preMax[i], sufMax[i]) - height[i];
        }
        return ans;
    }

    public static int trap1(int[] height) {
        int ans = 0;
        int len = height.length;
        int preMax = 0;
        int sufMax = 0;
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            preMax = Math.max(height[left], preMax);
            sufMax = Math.max(height[right], sufMax);
            if (preMax > sufMax) {
                ans += sufMax - height[right--];
            } else {
                ans += preMax - height[left++];
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        int trap = trap(arr);
        int trap1 = trap1(arr);
        System.out.println("trap = " + trap);
        System.out.println("trap = " + trap1);
    }
}
